<?php

namespace app\api\controller;

use app\common\controller\Wxpay;
use app\common\controller\Wxpay2;
use app\common\model\Help;
use app\common\model\Wechat;
use library\Controller;
use phpcode\QrCode;
use think\Db;
use think\Request;
use think\App;

class Mini extends Controller
{

    public $header;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $help = new Help();
        $this->header = $help->em_getallheaders();
    }


    // 获取微信小程序用户openid和session_key
    public function getOpenid(Wechat $wechat, Request $request, Help $help)
    {
        $wx_config = $wechat->mini_config($this->header);
        $code = $_POST['code'];                            //小程序传来的code值
        $appid = $wx_config['app_id'];                        //小程序的appid
        $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
        $wxUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $result = $help->curl_request($wxUrl);//请求拼接好的url
        if ($result) {
            echo json_encode(array('msg' => '成功', 'code' => 200, 'data' => json_decode($result)));
            exit;
        } else {
            echo json_encode(array('msg' => '失败', 'code' => 400));
            exit;
        }
    }

    // 获取用户信息
    public function getwechatuser()
    {
        //获取用户微信信息，包括昵称，头像等等
        $openid = $_POST['openid'];
        $unionid = $_POST['unionid'] ?? '';
        $sn = $_POST['sn'] ?? '';

        $gender = isset($_POST['gender']) ? $_POST['gender'] : 0;
        $avatar = isset($_POST['avatarUrl']) ? $_POST['avatarUrl'] : '';
        $nickname = isset($_POST['nickName']) ? $_POST['nickName'] : '';
        $rt = Db::table('store_member')->where('openid', $openid)->find();
        if ($rt) {
            if ($unionid) {
                Db::table('store_member')->where('openid', $openid)->update(['unionid' => $unionid]);
            }
        }


        if ($gender == 0) {
            $sex = '';
        } elseif ($gender == 1) {
            $sex = '男';
        } elseif ($gender == 2) {
            $sex = '女';

        }

        if (strlen($openid) != 28) {
            //用户再次登录
            $data = ['code' => 400, 'data' => [], 'msg' => '登录失败'];
            echo json_encode($data);
            exit;
        }

        //用户第一次登陆
        $time = date('Y-m-d H:i:s', time());
        if (empty($rt)) {
            $d = [
                'year' => date('Y'),
                'month' => date('m'),
                'openid' => $openid,//用户唯一标识
                'nickname' => $nickname,//昵称
                'headimg' => $avatar,//用户头像
                'sex' => $sex,//用户性别，1男2女 0未知
                'create_at' => $time
            ];
            Db::table('store_member')->insert($d);

            $rt = Db::table('store_member')->where('openid', $openid)->find();
            $rt = $this->check_fenxiao($rt['id'], $rt);

            if (empty($rt['headimg'])) {
                $rt['headimg'] = sysconf('realm_name') . '/static/theme/img/kong.png';
            }

            $this->bind($rt, $sn);
            $data = ['code' => 200, 'data' => $rt, 'msg' => '登录成功'];
            echo json_encode($data);
            exit;
        } else {
            $rt = $this->check_fenxiao($rt['id'], $rt);
            if (empty($rt['headimg'])) {
                $rt['headimg'] = sysconf('realm_name') . '/static/theme/img/kong.png';
            }
            $this->bind($rt, $sn);
            //用户再次登录
            $data = ['code' => 200, 'data' => $rt, 'msg' => '登录成功'];
            echo json_encode($data);
            exit;
        }
    }

    //上级绑定
    public function bind($rt, $sn)
    {
        if ($rt['id'] != $sn) {
            if ($sn) {
                $id = $rt['id'];
                if (empty($rt['parent_id'])) {
                    $find = Db::table("store_member")->field("id")->where("parnet_id=$id")->find();   //我下面已经有人了的情况下，我不能再有上级了
                    if (empty($find)) {
                        Db::table("store_member")->where("id=$id")->update(['parent_id' => $sn, 'parent_bind' => date('Y-m-d H:i:s')]);
                    }
                }
            }
        }
    }



    //轮播协议
    public function banner_find()
    {
        $id = $_POST['id'];
        $data = Db::table("system_banner")->where("id=$id")->find();
        echo json_encode($data);
        exit;
    }


    //协议
    public function xieyi()
    {
        $type = input('type')??1;

        if($type==1){
            $data = Db::table("store_state")->where("id=71890999345542")->find();
        }
        if($type==2){
            $data = Db::table("store_state")->where("id=71890999345543")->find();
        }
        if($type==3){
            $data = Db::table("store_state")->where("id=84558534709650")->find();
        }

        echo json_encode($data);
        exit;
    }

    public function floorToDecimal($number, $decimals) {
        $factor = pow(10, $decimals);
        return floor($number * $factor) / $factor;
    }

    //获取用户信息
    public function user()
    {
        $id = $_POST['id'];
        $find = Db::table("store_member")->where("id=$id")->find();
        if (empty($find['image'])) {
            $prefix = 'static/mall_member/';
            $id = $find['id'];

            $file_name = $prefix . 'mazhi_' . $id . '_0' . '.png';
            $result['file'] = sysconf('realm_name') . '/static/mall_member/' . 'mazhi_' . $id . '_0' . '.png';

            $url = 'https://' . $_SERVER['SERVER_NAME'] . '/sao.php?tjcode=000777&sn=' . $id;
            $image = $result['file'];

            Db::query("update store_member set image='$image',mazhi='$url' where id=$id");

            if (!file_exists($file_name)) {
                QrCode::getQrCode('mazhi_' . $id . '_0', $id, $prefix, '10', 'L', $url);
            }
        }

        if (empty($find['headimg'])) {
            $find['headimg'] = sysconf('realm_name') . '/static/theme/img/kong.png';
        }

        $find = $this->haibao($id, $find);

        if (empty($find['headimg'])) {
            $find['headimg'] = sysconf('realm_name') . '/static/theme/img/kong.png';
        }

        if($find['score']>=0.1){
            $find['dikou'] = $this->floorToDecimal(($find['score']*0.1),2);
        }else{
            $find['dikou'] = 0;
        }


        $find['region'] = explode(',', str_replace(' ', ',', $find['area']));
        $find = $this->check_fenxiao($find['id'], $find);


        echo json_encode($find);
    }

    //定时 码值生成海报
    public function haibao($id, $find)
    {
        $help = new Help();
        if (empty($find['qrcode'])) {
            $haibao = $help->qr_create($id, 'store_member', 1);
            $d['qrcode'] = $haibao;
            Db::table("store_member")->where("id=$id")->update($d);
        }
        $find = Db::table("store_member")->where("id=$id")->find();
        return $find;
    }

    //是否可进入分销会员
    public function check_fenxiao($id, $find)
    {
        $list = Db::query("select o.id,l.price_selling from store_order o left join store_order_list l on o.order_no=l.order_no where o.mid=$id and o.status in (3,4,5) and o.is_deleted=0"); //o.xieyi=1
        $price_selling = 0;
        foreach ($list as $k => &$v) {
            $price_selling += $v['price_selling'];
        }
        $find['price_selling'] = $price_selling;

        if ($find['price_selling'] >= 3) {
            $find['fenxiao'] = 'success';
        } else {
            $find['fenxiao'] = 3 - $find['price_selling'];
        }
        return $find;
    }

    //余额日志
    public function amount_log(Request $request){
        $param = $request->param();
        $find = Db::table("store_member_amount_log")->where(["user_id" => $param['user_id'],"is_pay"=>1])->order("id desc")->select();
        foreach ($find as $k =>&$v){
            $v['amount'] = sprintf('%.2f',$v['amount']);
        }
        echo json_encode($find);
    }

    //积分日志
    public function score_log(Request $request){
        $param = $request->param();
        $find = Db::table("store_member_score_log")->where(["user_id" => $param['user_id']])->order("id desc")->select();
        foreach ($find as $k =>&$v){
            $v['score'] = sprintf('%.2f',$v['score']);
        }
        echo json_encode($find);
    }


    //反馈
    public function feedback(Request $request){
        $param = $request->param();
        $param['create_at'] = date('Y-m-d H:i:s');
        Db::table("store_feedback")->insert($param);
        echo 1;
    }


    //反馈记录
    public function feedback_list(Request $request){
        $param = $request->param();
        $find = Db::table("store_feedback")->where(["user_id" => $param['user_id']])->order("id desc")->select();
        echo json_encode($find);

    }

    //用户详情
    public function user_info()
    {
        $id = $_POST['id'];
        $find = Db::table("store_member")->where("id=$id")->find();
        $find = $this->check_fenxiao($id, $find);
        $find['parent'] = Db::table("store_member")->where(["id" => $find['parent_id']])->find();

        if($find['score']>=0.1){
            $find['dikou'] = $this->floorToDecimal(($find['score']*0.1),2);
        }else{
            $find['dikou'] = 0;
        }

        $list = Db::table("store_order_pay")->where(["user_id"=>$id])->where("status","in","3")->order("id desc")->select();
        $order_ids = '';
        foreach ($list as $k =>&$v){
            $order_ids .= $v['id'].',';
        }
        $order_ids = trim($order_ids,',');

        $report_number = count(Db::table("store_order_report")->field("id")->where("order_id","in",$order_ids)->where("report_image is not null")->order("id desc")->select());

        Db::table("store_member")->where("id=$id")->update(['report_number'=>$report_number]);
        $find['report_number'] = $report_number;

        $help = new Help();
        $help->create_heading($id,$find['headimg']);
        echo json_encode($find);
    }


    //检测报告
    public function report_list(){
        $user_id = $_POST['user_id'];
        $order_id = $_POST['order_id']??'';
        $where = "";
        if($order_id){
            $where = "id=$order_id";
        }
        $list = Db::table("store_order_pay")->where(["user_id"=>$user_id])->where($where)->where("status","in","3")->order("id desc")->select();
        $order_ids = '';
        foreach ($list as $k =>&$v){
            $order_ids .= $v['id'].',';
        }
        $order_ids = trim($order_ids,',');

        $res = Db::table("store_order_report")->where("order_id","in",$order_ids)->where("report_image is not null")->order("id desc")->select();
        $arr = [];
        foreach ($res as $k =>&$vv){
            $vv['package'] = Db::table("store_package")->where(["id"=>$vv['package_id']])->where(["status" => 1, 'is_deleted' => 0])->find();
            $vv['package']['project'] = Db::table("store_goods_cate")->where("id","in",$vv['project_id'])->select();
            $vv['package']['project_id'] = $vv['project_id'];
            $vv['package']['time'] = $vv['file_time'];
            $vv['package']['order_id'] = $vv['order_id'];
            $vv['package']["report_id"] = $vv['id'];
            array_push($arr,$vv['package']);
        }

        echo json_encode($arr);
    }


    //更新用户信息
    public function userinfo()
    {
        $id = $_POST['id'];
        $find = Db::table("store_member")->where("id=$id")->find();

        $data = array();
        if (!empty($_POST['phone'])) {
            $data['phone'] = $_POST['phone'];
        }

        if (!empty($_POST['bank_number'])) {
            $data['bank_number'] = $_POST['bank_number'];
            if ($data['bank_number'] == 'undefined') {
                $data['bank_number'] = '';
            }
        }

        if (!empty($_POST['bank_address'])) {
            $data['bank_address'] = $_POST['bank_address'];
            if ($data['bank_address'] == 'undefined') {
                $data['bank_address'] = '';
            }
        }

        if (!empty($_POST['bank_name'])) {
            $data['bank_name'] = $_POST['bank_name'];
            if ($data['bank_name'] == 'undefined') {
                $data['bank_name'] = '';
            }
        }

        if (!empty($_POST['username'])) {
            $data['username'] = $_POST['username'];
            $data['nickname'] = $_POST['username'];
        }

        if (!empty($_POST['area'])) {
            if ($_POST['area'] != '请选择,请选择,请选择') {
                $data['area'] = str_replace(',', ' ', $_POST['area']);
            }
        }

        if (!empty($_POST['town'])) {
            if ($_POST['town'] != '请选择') {
                $data['town'] = $_POST['town'];
            }
        }

        if (!empty($_POST['address'])) {
            $data['address'] = $_POST['address'];
            if ($data['address'] == 'undefined') {
                $data['address'] = '';
            }
        }

        if (!empty($_POST['town_id'])) {
            $data['town_id'] = $_POST['town_id'];
            $data['express_area_id'] = Db::table("system_towns")->where(["code" => $data['town_id']])->value('parent_code');;
            if ($data['express_area_id']) {
                $data['express_city_id'] = Db::table("system_towns")->where(["code" => $data['express_area_id']])->value('parent_code');
                if ($data['express_city_id']) {
                    $data['express_province_id'] = Db::table("system_towns")->where(["code" => $data['express_city_id']])->value('parent_code');
                }
            }
        }

        $d['platform'] = $_POST['platform'] ?? '';

        if (!empty($_POST['front_card'])) {
            if (!$this->is_not_json($_POST['front_card'])) {
                if (!empty(json_decode($_POST['front_card'], true)[0])) {
                    $d['front_card'] = json_decode($_POST['front_card'], true)[0];
                } else {
                    $d['front_card'] = '';
                }
            } else {
                $d['front_card'] = $_POST['front_card'];
            }
            if (empty($d['front_card'])) {
                unset($d['front_card']);
            }
        }

        if (!empty($_POST['back_card'])) {
            if (!$this->is_not_json($_POST['back_card'])) {
                if (!empty(json_decode($_POST['back_card'], true)[0])) {
                    $d['back_card'] = json_decode($_POST['back_card'], true)[0];
                } else {
                    $d['back_card'] = '';
                }
            } else {
                $d['back_card'] = $_POST['back_card'];
            }
            if (empty($d['back_card'])) {
                unset($d['back_card']);
            }
        }


        if (!empty($_POST['headimg'])) {
            if (!$this->is_not_json($_POST['headimg'])) {
                if (!empty(json_decode($_POST['headimg'], true)[0])) {
                    $d['headimg'] = json_decode($_POST['headimg'], true)[0];
                } else {
                    $d['headimg'] = '';
                }
            } else {
                $d['headimg'] = $_POST['headimg'];
            }

            if ($d['headimg']) {
                if ($find['headimg'] != $d['headimg']) {
                    $dt['headimg'] = $d['headimg'];
                    Db::table("store_member")->where("id=$id")->update($dt);
                    $help = new Help();
                    $haibao = $help->qr_create($id, 'store_member', 1);
                    $dd['qrcode'] = $haibao;
                    Db::table("store_member")->where("id=$id")->update($dd);
                }
            } else {
                unset($d['headimg']);
            }
        }

        if (!empty($_POST['nickname'])) {
            $d['nickname'] = $_POST['nickname'];
            if ($find['nickname'] != $d['nickname']) {
                $dt['nickname'] = $d['nickname'];
                Db::table("store_member")->where("id=$id")->update($dt);
                $help = new Help();
                $haibao = $help->qr_create($id, 'store_member', 1);
                $dd['qrcode'] = $haibao;
                Db::table("store_member")->where("id=$id")->update($dd);
            }
        }

        $find = Db::table("store_member")->where("id=$id")->find();
        if ($find) {
            if ($d['platform'] == 'getUserProfile') {
                if (empty($find['platform'])) {
                    Db::table("store_member")->where("id=$id")->update($d);
                }
            } else {
                Db::table("store_member")->where("id=$id")->update($d);
            }
            if (!empty($data)) {
                Db::table("store_member")->where("id=$id")->update($data);
            }
        }

        echo 1;
    }

    //是不是json
    public function is_not_json($str)
    {
        return is_null(json_decode($str));
    }

    //删除用户信息
    public function deluser()
    {
        $id = $_POST['id'];
        $data['is_deleted'] = 1;
        Db::table("store_member")->where("id=$id")->update($data);
    }

    //上传图片
    public function uploads($path = "static/uploads/mini/")
    {
        $help = new Help();

        $filename = 'upfile';
        $pic_path = '';
        $picname = $_FILES[$filename]['name'];
        $picsize = $_FILES[$filename]['size'];
        if ($picname != "") {
            $type = $help->getSuffix($picname);
            if ($type != 'jpg' && $type != 'gif' && $type != 'png' && $type != 'jpeg' && $type != 'JPG' && $type != 'PNG' && $type != 'JPEG') {
                $array = array(
                    'name' => '格式错误,请上传jpg,gif,png,jpeg',
                    'pic' => '',
                    'size' => '',
                    'pic_path' => ''
                );
                return json_encode($array);
            }
            $type = '.' . $type;
            $md5 = md5(uniqid());
            $pics = $md5 . $type;
            $path = $help->create_dir($path);
            $pic_path = strtr($path, array('./' => '')) . $pics;
            move_uploaded_file($_FILES[$filename]['tmp_name'], $pic_path);
        }

        $shuxing = @getimagesize($pic_path);
        if (!empty($shuxing)) {
            $width = (int)$shuxing[0];
            $height = (int)$shuxing[1];
            $w = 750;
            $h = 750 * $height / $width;
        } else {
            $w = $h = 750;
        }

        if (file_exists($pic_path)) {
            $image_small = $help->resize_image($pic_path, $path, $w, $h);
        } else {
            $image_small = $pic_path;
        }

        $size = round($picsize / 1024, 2);
        $arr = array(
            'name' => $picname,
            'pic' => $image_small,
            'size' => $size,
            'pic_path' => $image_small,
            'pic_small' => $image_small
        );
        return sysconf('realm_name') . '/' . $arr['pic'];
    }

    //导航
    public function icon_list()
    {
        $data['status'] = 1;
        $data['is_deleted'] = 0;
        $list = Db::table("system_icon")->field("id,title,logo")->where($data)->select();
        echo json_encode($list);
        exit;
    }


    //轮播图
    public function banner_list()
    {
        $data['cate_id'] = 1;
        $data['status'] = 1;
        $data['is_deleted'] = 0;
        $list = Db::table("system_banner")->field("id,title,logo")->where($data)->select();
        foreach ($list as $k => &$v) {
            $v['slide_url'] = $v['logo'];
        }
        echo json_encode($list);
        exit;
    }

    //套餐
    public function package()
    {
        $data['status'] = 1;
        $data['is_deleted'] = 0;
        $cate_id = input('cate_id')??0;
        $keyword = input('keyword')??'';
        $index = input('index')??'0';

        $where = "sort>=0";
        if($cate_id){
            $where .= " and find_in_set($cate_id,cate_id)";
        }
        if($keyword){
            $where .= " and (cate_name like '%$keyword%' or symptom_name  like '%$keyword%' or project_name  like '%$keyword%')";
        }
        if($index==2){
            $where .= " and brand_name like '%基因检测%' ";
        }
        if($index==3){
            $where .= " and brand_name like '%疾病检测%' ";
        }
        if($index==4){
            $where .= " and brand_name like '%健康检测%' ";
        }

        $list = Db::table("store_package")->where($data)->where($where)->order("id desc")->select();
        foreach ($list as $k =>&$v){
            $v['total_price'] = Db::table("store_goods_cate")->where("id","in",$v['project_id'])->sum('price');
        }
        echo json_encode($list);
        exit;
    }


    //品系
    public function cate()
    {
        $data['pid'] = 1;
        $data['status'] = 1;
        $data['is_deleted'] = 0;
        $list = Db::table("store_goods_cate")->field("id,title,logo")->where($data)->order("id desc")->select();
        echo json_encode($list);
        exit;
    }


    //项目
    public function project()
    {
        $data['pid'] = 30;
        $data['status'] = 1;
        $data['is_deleted'] = 0;
        $list = Db::table("store_goods_cate")->field("id,title,logo")->where($data)->order("id desc")->select();
        echo json_encode($list);
        exit;
    }


    //症状
    public function symptom()
    {
        $data['pid'] = 11;
        $data['status'] = 1;
        $data['is_deleted'] = 0;
        $list = Db::table("store_goods_cate")->field("id,title,logo")->where($data)->order("id desc")->select();
        echo json_encode($list);
        exit;
    }


    //添加套餐购物车
    public function insert_cart()
    {
        $d['package_id'] = $_POST['id'];
        $d['project_id'] = trim($_POST['project_id'],',');
        $d['total_price'] = Db::table("store_goods_cate")->where("id","in",$d['project_id'])->sum('price')??0;
        $d['user_id'] = $user_id = $_POST['user_id'];
        $d['create_at'] = date('Y-m-d H:i:s');
        Db::table("store_cart")->insert($d);
        $count = Db::table("store_cart")->where(['user_id'=>$user_id])->count();
        echo $count;
    }

    //添加套餐购物车
    public function insert_cart2()
    {
        Db::table("store_cart2")->where(["user_id"=>$_POST['user_id']])->delete();
        $d['package_id'] = $_POST['id'];
        $d['project_id'] = trim($_POST['project_id'],',');
        $d['total_price'] = Db::table("store_goods_cate")->where("id","in",$d['project_id'])->sum('price')??0;
        $d['user_id'] = $user_id = $_POST['user_id'];
        $d['create_at'] = date('Y-m-d H:i:s');
        Db::table("store_cart2")->insert($d);
        $count = Db::table("store_cart2")->where(['user_id'=>$user_id])->count();
        echo $count;
    }

    //套餐详情
    public function package_info(){
        $id = $_POST['id'];
        $v = Db::table("store_package")->where("id=$id")->where(["status" => 1, 'is_deleted' => 0])->find();
        if($v['project_id']){
            $v['project'] = Db::table("store_goods_cate")->where("id","in",$v['project_id'])->select();
            foreach ($v['project'] as $kk =>&$vv){
                $vv['selected'] = '';
            }
            $v['project_count'] = count($v['project']);
        }else{
            $v['project'] = [];
            $v['project_count'] = 0;
        }

        echo json_encode($v);
        exit;
    }

    //套餐结算
    public function cart_pay(){
        $type = $_POST['type']??1;
        $ids = trim($_POST['ids'],',');
        if($type==1){
            $list = Db::table("store_cart")->where("id" ,"in",$ids)->select();
        }else{
            $list = Db::table("store_cart2")->where("user_id" ,"in",$_POST['user_id'])->select();
        }

        $total = 0;
        foreach ($list as $k =>&$v){
            $total += $v['total_price'];
            $v['package'] = Db::table("store_package")->where(['id'=>$v['package_id']])->find();
            $v['project'] = Db::table("store_goods_cate")->where("id","in",$v['project_id'])->select();
        }
        echo json_encode(['list'=>$list,'count'=>count($list),'total'=>sprintf('%.2f',$total)]);
    }

    //套餐购物车列表
    public function cart()
    {
        $list = Db::table("store_cart")->where(["user_id" => $_POST['user_id']])->select();
        foreach ($list as $k =>&$v){
            $v['package'] = Db::table("store_package")->where(['id'=>$v['package_id']])->find();
            $v['project'] = Db::table("store_goods_cate")->where("id","in",$v['project_id'])->select();
            $v['selected'] = false;
        }
        echo json_encode(['list'=>$list,'total_goods_sum'=>count($list)]);
    }

    //套餐购物车数量
    public function cart_count(){
        $user_id = $_POST['user_id'];
        $count = Db::table("store_cart")->where(['user_id'=>$user_id])->count();
        echo $count;
    }


    //删除商品购物车
    public function delcart()
    {
        Db::table("store_cart")->where(["id" => $_POST['id']])->delete();
    }
    //删除商品购物车
    public function delcarts()
    {
        $ids = trim($_POST['id'], ',');
        if ($ids) {
            Db::table("store_cart")->where("id", "in", $ids)->delete();
        }
    }












    //全部商品
    public function goods_lists()
    {
        $title = $_POST['searchInput'] ?? '';
        $data['status'] = 1;
        $data['is_deleted'] = 0;
        $page = $_POST['page'] ?? 1;
        $page = ($page - 1) * 10;
        $pagesize = $_POST['pagesize'] ?? 10;

        $list = Db::table("store_goods")->field("id,title,logo,text_id")->where("title like '%$title%'")->where($data)->limit($page, $pagesize)->select();
        foreach ($list as $k => &$v) {
            $v['header'] = $v['title'];
            $v['goods_cover'] = $v['logo'];
            $spec = Db::table("store_goods_list")->where(['goods_id' => $v['id'], 'status' => 1])->find();
            $v['meta'] = $spec['price_selling'];
            $v['discount'] = $spec['price_market'];
        }

        echo json_encode($list);
        exit;
    }


    //商品详情
    public function goods_info()
    {
        $id = $_POST['id'];
        $list = Db::table("store_goods")->field("id,title,logo,image,number_sales,intro,content")->where("id=$id")->where(["status" => 1, 'is_deleted' => 0])->find();
        $list['goods_list'] = Db::table("store_goods_list")->where("goods_id=$id")->where(["status" => 1])->select();

        $list['images'] = explode(',', $list['image']);
        $arr = $goods_slides = [];
        foreach ($list['images'] as $k => &$v) {
            $arr['id'] = $k;
            $arr['slide_url'] = $v;
            $goods_slides[] = $arr;
        }
        $list['description'] = '';
        $list['goods_slides'] = $goods_slides;
        $list['header'] = $list['title'];
        $list['intro_img'] = $list['parameter_img'] = [];

        if ($list['goods_list']) {
            $goods_spec = $list['goods_list'][0]['goods_spec'];
            $spec = explode('::', $goods_spec)[1];
            $list['meta'] = $list['goods_list'][0]['price_selling'];
            $list['default'] = array($spec, '', 1, $list['meta'], $list['goods_list'][0]['id'], ($list['goods_list'][0]['number_stock'] - $list['goods_list'][0]['number_sales']));
            $list['market'] = $list['goods_list'][0]['price_market'];
            $list['kucun'] = $list['goods_list'][0]['number_stock'] - $list['goods_list'][0]['number_sales'];

            $version = [];
            foreach ($list['goods_list'] as $k => &$v) {
                $array['name'] = explode('::', $v['goods_spec'])[1];
                $array['value'] = [explode('::', $v['goods_spec'])[1], $v['price_selling'], $v['price_market'], $v['id'], ($v['number_stock'] - $v['number_sales'])];
                $version[] = $array;
            }

            $list['attr_list'] = ['color' => [], 'version' => $version];
        }

        echo json_encode($list);
    }

    //添加商品购物车
    public function add_cart()
    {
        $spec = explode(',', $_POST['goods_default']);
        $d['goods_id'] = $goods_id = $_POST['id'];
        $d['spec_id'] = $spec_id = $spec[4];
        $d['goods_spec'] = $spec[0];
        $d['number'] = $number = $spec[2];
        $d['money'] = $money = $spec[3];
        $d['user_id'] = $user_id = $_POST['user_id'];
        $d['create_at'] = date('Y-m-d H:i:s');
        $d['type'] = $type = $_POST['type'] ?? 0;

        $ishave = Db::table("store_shopping_cart")->where(["spec_id" => $spec_id, "user_id" => $_POST['user_id'], "type" => $_POST['type']])->find();

        if ($ishave) {
            if ($type == 0) {
                Db::query("update store_shopping_cart set number=number+$number,money=$money,goods_id=$goods_id where `type`=$type and spec_id='$spec_id' and user_id='$user_id' ");
            } else {
                Db::query("update store_shopping_cart set number=$number,money=$money,goods_id=$goods_id where `type`=$type and spec_id='$spec_id' and user_id='$user_id' ");
            }

        } else {
            Db::table("store_shopping_cart")->insert($d);
        }

        $count = 0;
        $store_shopping_cart = Db::query("select sum(number) total_number from store_shopping_cart where user_id=$user_id and type=0");
        if (!empty($store_shopping_cart)) {
            if (!empty($store_shopping_cart[0])) {
                $count = $store_shopping_cart[0]['total_number'];
            }
        }

        if ($type == 0) {
            echo $count;
        } else {
            $ishave = Db::table("store_shopping_cart")->where(["spec_id" => $spec_id, 'type' => $_POST['type'], "user_id" => $_POST['user_id']])->find();
            echo $ishave['id'];
        }
    }

    //商品购物车列表
    public function cart_list()
    {
        $list = Db::table("store_shopping_cart")->alias("c")->field("c.*,g.title,g.logo cover")->leftJoin('store_goods g', 'c.goods_id=g.id')->where(["user_id" => $_POST['user_id']])->where("c.type=0")->select();
        foreach ($list as $k => &$v) {
            $v['price'] = $v['money'];
            $v['goods_name'] = $v['title'];
            $v['color'] = '';
            $v['isTouchMove'] = false;
            $v['selected'] = false;
            $v['memory'] = $v['goods_spec'];
            $v['select_num'] = $v['number'];
        }
        echo json_encode($list);
    }

    
    //修改商品购物车
    public function edit_cart()
    {
        $id = $_POST['id'];
        $num = $_POST['num'];
        Db::table("store_shopping_cart")->where("id", "in", $id)->update(['number' => $num]);
    }


    //商品购物车列表
    public function cart_list_select()
    {
        $ids = trim($_POST['ids'], ' ');
        $ids = trim($ids, ',');

        $list = Db::table("store_shopping_cart")->alias("c")->field("c.*,g.title,g.logo")->leftJoin('store_goods g', 'c.goods_id=g.id')->where(["user_id" => $_POST['user_id']])->where("c.id", "in", $ids)->select();
        $total = 0;
        $goods_num = 0;
        foreach ($list as $k => &$v) {
            $v['is_sku'] = Db::table("store_goods_list")->where(['id' => $v['spec_id']])->value('is_sku');
            $v['price'] = $v['money'];
            $v['goods_name'] = $v['title'];
            $v['color'] = '';
            $v['isTouchMove'] = false;
            $v['selected'] = false;
            $v['memory'] = $v['goods_spec'];
            $v['select_num'] = $v['number'];
            $goods_num += $v['number'];
            $total += $v['number'] * $v['money'];
        }

        echo json_encode(['list' => $list, 'total' => sprintf('%.2f', $total), 'goods_num' => $goods_num]);
    }


    //我的默认地址
    public function MyDefaultAddress()
    {
        $res = Db::table('store_user_address')->where(array('user_id' => $_POST['user_id'], 'is_default' => 1))->find();
        echo json_encode($res);
    }

    //系统
    public function System()
    {
        $wechat = new Wechat();
        $wx_config = $wechat->mini_config($this->header);
        $wx_config['dingjin'] = Db::table("system_config")->where("id=94")->value('value');
        $wx_config['baozhengjin'] = Db::table("system_config")->where("id=95")->value('value');
        echo json_encode($wx_config);
    }

    //系统
    public function Systems()
    {
        $wx_config['dingjin'] = Db::table("system_config")->where("id=94")->value('value');
        $wx_config['baozhengjin'] = Db::table("system_config")->where("id=95")->value('value');
        $wx_config['tixian'] = Db::table("system_config")->where("id=96")->value('value');
        $wx_config['yinsi'] = Db::table("store_state")->where("id=71890999345543")->value('content');
        echo json_encode($wx_config);
    }

    //我的地址
    public function MyAddress()
    {
        $res = Db::table('store_user_address')->where(array('user_id' => $_POST['user_id']))->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]['area'] = explode(',', $res[$i]['area']);
        }
        echo json_encode($res);
    }


    //删除地址
    public function DelAdd()
    {
        $id = $_POST['id'];
        Db::query("delete from store_user_address where id=$id");
        echo '1';
    }

    //设为地址默认
    public function AddDefault()
    {
        $data['is_default'] = 1;
        $id = $_POST['id'];
        $add = Db::table('store_user_address')->where(array('id' => $_POST['id']))->find();
        Db::table('store_user_address')->where(array('id' => $_POST['id']))->update($data);

        $d['is_default'] = 2;
        Db::table('store_user_address')->where(array('user_id' => $add['user_id']))->where("id != $id")->update($d);
        echo 1;
    }

    //我的地址详情
    public function MyAddressInfo()
    {
        $res = Db::table('store_user_address')->where(array('id' => $_POST['id']))->find();
        $res['area'] = explode(',', $res['area']);
        echo json_encode($res);
    }

    //添加地址
    public function AddAddress()
    {
        if (empty($_POST['sex'])) {
            $_POST['sex'] = 0;
        }

        $data['address'] = $_POST['address'];
        $data['area'] = $_POST['area'];
        $data['user_name'] = $_POST['user_name'];
        $data['user_id'] = $_POST['user_id'];
        $data['sex'] = $_POST['sex'];
        $data['tel'] = $_POST['tel'];
        $data['lat'] = $_POST['lat'];
        $data['lng'] = $_POST['lng'];
        $data['remark'] = $_POST['remark'] ?? '';
        $data['town'] = $_POST['town'] ?? '';
        $data['town_id'] = $_POST['town_id'] ?? '';

        $data['is_default'] = 1;

        Db::table('store_user_address')->insert($data);

        $res = Db::table('store_user_address')->where(array('user_id' => $_POST['user_id']))->where(array('is_default' => 1))->order("id desc")->find();

        $id = $res['id'];
        if ($res) {
            $d['is_default'] = 2;
            Db::table('store_user_address')->where(array('user_id' => $_POST['user_id']))->where("id != $id")->update($d);
            echo '1';
        } else {
            echo '2';
        }
    }

    //修改地址
    public function UpdAddress()
    {
        if (empty($_POST['sex'])) {
            $_POST['sex'] = 0;
        }

        $data['address'] = $_POST['address'];
        $data['area'] = $_POST['area'];
        $data['user_name'] = $_POST['user_name'];
        $data['tel'] = $_POST['tel'];
        $data['sex'] = $_POST['sex'];
        $data['lat'] = $_POST['lat'];
        $data['lng'] = $_POST['lng'];
        $data['remark'] = $_POST['remark'] ?? '';
        $data['town'] = $_POST['town'] ?? '';
        $data['town_id'] = $_POST['town_id'] ?? '';

        $w['id'] = $_POST['id'];
        Db::table('store_user_address')->where($w)->update($data);
        echo '1';
    }

    //数组化简
    public function row_array($result)
    {
        if (!empty($result)) {
            if (!empty($result[0])) {
                return $result[0];
            } else {
                return null;
            }
        } else {
            return null;
        }
    }


    //查看区域
    public function select_region()
    {
        $list = Db::table("system_citys")->where("id", "in", "230000,220000,210000,150000")->field("id,name")->select();
        $arr = [['name' => '请选择地区', 'cities' => [['name' => '', 'areas' => ['']]]]];
        foreach ($list as $k => &$v) {
            $cities = Db::table("system_citys")->where(["p_id" => $v['id']])->field("id,name")->select();
            foreach ($cities as $kk => &$vv) {
                $area_array = [];
                $area = Db::table("system_citys")->where(["p_id" => $vv['id']])->field("id,name")->select();
                foreach ($area as $kkk => &$vvv) {
                    array_push($area_array, $vvv['name']);
                }
                $vv['areas'] = $area_array;
            }

            array_push($arr, ['name' => $v['name'], 'cities' => $cities]);
        }
        echo json_encode($arr);
    }


    //区域 街道
    public function region()
    {

        if (empty($_POST['region'])) {
            echo json_encode(['id' => [], 'name' => []]);
            exit;
        }

        if (strstr($_POST['region'], ',')) {
            $region = explode(',', $_POST['region']);
        } else {
            $region = explode(' ', $_POST['region']);
        }

        $province = $region[0];
        $city = $region[1];
        $area = $region[2];

        $p = Db::table("system_towns")->where("name='$province'")->where("level_type=1")->find();
        $p_code = $p['code'];
        $arr = [];
        $arrs = [];

        if ($p) {
            if ($province == $city) {
                $c = $this->row_array(Db::query("select * from system_towns where (name='市辖区' or name='县') and parent_code=$p_code"));
            } else {
                $c = Db::table("system_towns")->where("name = '$city' and parent_code=$p_code")->where("level_type=2")->find();
            }

            if ($c) {
                $c_code = $c['code'];
                $area = str_replace('区', '', $area);
                $c_code1 = $c_code + 100;
                $a = Db::table("system_towns")->where("name like '%$area%' and parent_code=$c_code")->where("level_type=3")->find();

                if (empty($a)) {
                    $a = Db::table("system_towns")->where("name like '%$area%' and parent_code=$c_code1")->where("level_type=3")->find();
                }

                if ($a) {
                    $code = $a['code'];
                    $list = Db::table("system_towns")->where("parent_code='$code'")->select();
                    foreach ($list as $k => &$v) {
                        $arr[] = $v['code'];
                        $arrs[] = $v['name'];
                    }
                }
            }
        }
        echo json_encode(['id' => $arr, 'name' => $arrs]);

    }


    //过滤特殊字符
    function encryptName($name)
    {
        $encrypt_name = '';
        //判断是否包含中文字符
        if (preg_match("/[\x{4e00}-\x{9fa5}]+/u", $name)) {
            //按照中文字符计算长度
            $len = mb_strlen($name, 'UTF-8');
            //echo '中文';
            if ($len >= 3) {
                //三个字符或三个字符以上掐头取尾，中间用*代替
                $encrypt_name = mb_substr($name, 0, 1, 'UTF-8') . str_repeat('*', $len - 2) . mb_substr($name, -1, 1, 'UTF-8');
            } elseif ($len === 2) {
                //两个字符
                $encrypt_name = mb_substr($name, 0, 1, 'UTF-8') . '*';
            }
        } else {
            //按照英文字串计算长度
            $len = strlen($name);
            //echo 'English';
            if ($len >= 3) {
                //三个字符或三个字符以上掐头取尾，中间用*代替
                $encrypt_name = substr($name, 0, 1) . str_repeat('*', $len - 2) . substr($name, -1);
            } elseif ($len === 2) {
                //两个字符
                $encrypt_name = substr($name, 0, 1) . '*';
            }
        }
        return $encrypt_name;
    }


    //客服电话
    public function kefu()
    {
        $phone = sysconf('contact_phone');
        echo json_encode($phone);
        exit;
    }


    //token
    public function token()
    {
        $wechat = new Wechat();
        $wx_config = $wechat->mini_config($this->header);
        $appid = $wx_config['app_id'];
        $token = Db::table("yz_access_token")->where("id=2")->find();
        if ($token) {
            $time1 = strtotime($token['time']);
            $time2 = time();
            $cha = $time2 - $time1;
            if ($cha > 3600) {
                $this->header = ['Appid' => $appid];
                $wx_config = $wechat->mini_config($this->header);
                $appid = $wx_config['app_id'];                        //小程序的appid
                $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";

                $result = $this->http_request($url);
                $access_token = json_decode($result)->access_token;
                Db::table("yz_access_token")->where("id=2")->update(['access_token' => $access_token, 'time' => date('Y-m-d H:i:s')]);
                return $access_token;

            } else {
                return $token['access_token'];
            }
        } else {
            $this->header = ['Appid' => $appid];
            $wx_config = $wechat->mini_config($this->header);
            $appid = $wx_config['app_id'];                        //小程序的appid
            $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";

            $result = $this->http_request($url);
            return $access_token = json_decode($result)->access_token;
        }

    }

    //获取手机号
    public function get_phone()
    {
        $code = $_POST['code'];
        $token = $this->token();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $data['code'] = $code;
        $result = $this->http_request($url, json_encode($data));
        $str = '';
        if (!empty($result)) {
            if (!empty(json_decode($result))) {
                if (!empty(json_decode($result)->phone_info)) {
                    if (!empty(json_decode($result)->phone_info->phoneNumber)) {
                        $phone = json_decode($result)->phone_info->phoneNumber;
                        if ($phone) {
                            //$id = $_POST['user_id'];
                            //Db::table("store_member")->where("id=$id")->update(["phone" => $phone]);
                            $str = json_encode($phone);
                        }
                    }
                }
            }
        }
        echo $str;
    }


    function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    //查看商品库存
    public function check_kucun()
    {
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }
        $id = $_POST['user_id'];
        $cart_id = trim($_POST['ids'], ',');
        $flag = 0;
        $list = Db::query("select * from store_shopping_cart where user_id=$id and id in ($cart_id)");
        foreach ($list as $k => &$v) {
            $v['spec'] = Db::table("store_goods_list")->where(["id" => $v['spec_id']])->find();
            if ($v['spec']) {
                $cha = $v['spec']['number_stock'] - $v['spec']['number_sales'];
                if ($cha < 0) {
                    $flag = 1;
                }
                if ($cha < $v['number']) {
                    $flag = 1;
                }
            }
        }
        echo $flag;
    }

    //查看商品库存
    public function check_stock()
    {
        $goods_default = explode(',', $_POST['goods_default']);
        $user_id = $_POST['user_id'];
        $spec_id = $goods_default[4];
        $cart = Db::table("store_shopping_cart")->where("user_id=$user_id")->where("spec_id=$spec_id")->find();
        $cart_num = 0;
        if ($cart) {
            $cart_num = $cart['number'];
        }
        $select_num = $goods_default[2];
        $kucun = $goods_default['5'];
        $sum = $cart_num + $select_num;
        if ($sum > $kucun) {
            $flag = 1;
        } else {
            $flag = 0;
        }
        echo $flag;
    }





    //我的
    public function mine()
    {
        $id = $_POST['id'];
        $list = Db::table("store_member")->where(['id' => $id])->find();
        $list['gg'] = sysconf('gg');
        echo json_encode($list);
    }


    //省
    public function province_list()
    {
        $list = Db::table("system_towns")->where(["level_type" => 1])->select();
        $arr = [];
        foreach ($list as $k => &$v) {
            array_push($arr, $v['name']);
        }

        echo json_encode($arr);
    }

    //市
    public function city_list()
    {
        $province = $_POST['province'] ?? '';
        $province_id = Db::table("system_towns")->where(["level_type" => 1])->where("name='$province'")->value('code');
        $list = Db::table("system_towns")->where(["level_type" => 2])->where("parent_code='$province_id'")->select();
        $arr = [];
        foreach ($list as $k => &$v) {
            array_push($arr, $v['name']);
        }

        echo json_encode($arr);
    }

    //区
    public function district_list()
    {
        $city = $_POST['city'] ?? '';
        $city_id = Db::table("system_towns")->where(["level_type" => 2])->where("name='$city'")->value('code');
        $list = Db::table("system_towns")->where(["level_type" => 3])->where("parent_code='$city_id'")->select();
        $arr = [];
        foreach ($list as $k => &$v) {
            array_push($arr, $v['name']);
        }

        echo json_encode($arr);
    }

    //区域 街道
    public function regions()
    {
        $district = $_POST['district'] ?? '';
        $district_id = Db::table("system_towns")->where(["level_type" => 3])->where("name='$district'")->value('code');
        $list = Db::table("system_towns")->where(["level_type" => 4])->where("parent_code='$district_id'")->select();
        $ar = $arr = [];
        foreach ($list as $k => &$v) {
            array_push($ar, $v['code']);
            array_push($arr, $v['name']);
        }

        echo json_encode(['id' => $ar, 'name' => $arr]);

    }


}